<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2023/11/20} {10:28} 
 */

namespace app\index\controller;


use app\api\controller\BaseCommonController;
use app\api\logic\ai\AiGoodsLogic;
use app\api\logic\UserLogic;
use app\common\model\TabConf;
use app\index\logic\alibaba\AlibabaAuth;
use app\index\logic\alibaba\distributes\strict\StrictOrder;
use app\index\logic\alibaba\distributes\Testexample;
use app\index\logic\WechatPayLogic;
use think\Controller;
use think\Db;
use think\facade\Request;
use wanghua\general_utility_tools_php\alibaba\distributes\strict\StrictGoods;
use wanghua\general_utility_tools_php\api\Api;
use wanghua\general_utility_tools_php\api\ApiDocument;
use wanghua\general_utility_tools_php\gpt\chat\F37A49CDED4199801B05D5FFFAF78E010;
use wanghua\general_utility_tools_php\http\Curl;
use wanghua\general_utility_tools_php\tool\Bank;
use wanghua\general_utility_tools_php\tool\Tools;
use wanghua\general_utility_tools_php\wechat\UserAuth;

/**
 * @deprecated
 */
class Test extends Controller
{
    function test()
    {


        die;

        dump(json_decode($goods_list['data'],true));
        die;

        $alipayConfig = aliPayWapH5ConfPublicAcc();
        $appid = $alipayConfig['app_id'];
        $url = 'https://meebomid.playone.cn/paytool/paymenttool/index/partner_id/1';
        // 强制支付宝客户端打开（新增代码）
        $alipayScheme = "alipays://platformapi/startapp?appId={$appid}&url=";
        $redirectUrl = $alipayScheme . urlencode($url);
echo $redirectUrl;die;
        // 输出自动跳转页面
        $html = <<<EOF
<html>
<head>
    <meta http-equiv="refresh" content="0;url=$redirectUrl">
</head>
<body></body>
</html>
EOF;
        echo $html;die;



        $code = '071alq0w35gae43o0H0w3W9thu4alq0I';

        $wxconfig = wxJsapiPayConfPublicAcc();
        //
        $userAuth = new UserAuth($wxconfig);
        //token交换openid
        $res = $userAuth->usrAccessToken($code);
        dump($res);
        if(isset($res['errcode'])&&$res['errcode']=='40163'){
            return json(Tools::set_fail('code已失效'));
        }
        if(empty($res['openid'])){
            return json(Tools::set_res(152,'微信授权失败'));
        }
        $openid = $res['openid'];
        $AccessToken = $userAuth->getAccessToken();
        dump($AccessToken);
        $res = $userAuth->getWeixinV2UserInfo($openid);
dump($res);
        die;
        //通过 code 获取 access_token
        $code = '091svOkl2q3PTe4J4qml2El1Fb3svOkk';
        $APPID = 'wx5904518b3a0b2965';
        $SECRET = '6b05e88e38281fc740712c51fb7e6c48';
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$APPID}&secret={$SECRET}&code={$code}&grant_type=authorization_code";
        $res = Curl::curl_get($url);
        dump($res);;
        $arr = json_decode($res['data'], true);
        if(isset($arr['errcode']) && $arr['errcode'] == 40163){

            dump('code been used');die;
        }

        $arr = json_decode($res['data'], true);
        //通过 access_token 获取用户信息
        $ACCESS_TOKEN = $arr['access_token'];
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$ACCESS_TOKEN}&openid=or9D2vqQ6Qd3DwYkIOxH6Tzrd34o";
        $res = Curl::curl_get($url);
        dump($res);die;

        dump(empty(trim(' ')));die;
        $initialTime = '2024-11-18 09:50:13';
        $targetTime = '2024-11-16 21:49:48';
        $res = Tools::time_to_day_hour_min_sec($initialTime,$targetTime);
            dump($res);

        $timeout = '20241115095013000';
        dump(date('Y-m-d H:i:s',strtotime($timeout/1000)));die;

        $arr = [1,2,45,55];
        echo json_encode($arr);die;

        //退款
        //$config = wxConfOrderPayFirm();
        ////dump($config);
        //$orderid = 'phuzhe9n1725089504331';
        //$reason = '测试退款';
        //$order_info = Db::table(TabConf::$fa_order)->where('orderid',$orderid)->find();
        //$res = (new WechatPayLogic())->toWxRefund($config,$order_info,$reason);
        //dump($res);
        //die;

        //查询退款单
        $config = wxJsapiPayConfPublicAcc();
        $orderid = 'phuzhe9n1725089504331';
        $res = (new WechatPayLogic())->toWxRefundQuery($config,$orderid);
        dump($res);
        die;



        echo substr("Hello world",-1)."<br>";
        //echo substr("Hello world",1,8)."<br>";
        //echo substr("Hello world",0,5)."<br>";
        //echo substr("Hello world",6,6)."<br>";

        echo substr("Hello world",0,-2)."<br>";
        //echo substr("Hello world",-10,-2)."<br>";
        //echo substr("Hello world",0,-6)."<br>";
        //echo substr("Hello world",-2-3)."<br>";
        die;
        dump(session('wx_user_info'));die;
        $Testexample = new Testexample();

        //$res = $Testexample->getLogisticsTemplate();
        //dump($res);die;
        $res = $Testexample->getLogisticsTemplateDetail(11864709);
        dump($res);die;

        //$res = $Testexample->getGoodsList(['categoryId'=>67]);
        //dump($res);die;

        //$res = $Testexample->getCategoryByCID('130822220');
        //$res = $Testexample->testGetRootCategory();
        //dump($res);


        //(new Testexample())->createOrder();
        //return $Testexample->testWebAuth(url('Alibaba/webUserAuth','',false,true));
        //dump($res);

    }

    /**
     * desc：用table 打印出商品列表
     * author：wh
     */
    function echogoods(){
        //查询商品
        $config = config('meebo_supply_config');
        $authObj = new \wanghua\general_utility_tools_php\alibaba\AlibabaAuth($config);
        $obj = new StrictGoods($authObj);
        $where['priceStart'] = 1;
        $where['priceEnd'] = 10;
        $where['pageNum'] = input('current_page',1);
        $where['pageSize'] = 20;//input('list_rows',20);//
        $result = $obj->getGoodsList($where);
        $result = json_decode($result['data'],true);
        $goods_list = $result['result']['result'];
//dump($goods_list);die;
        // 替换原有的dump语句
// die;

        echo '<table border="1" cellpadding="8" style="border-collapse: collapse; margin:20px 0; font-size:14px;">';
        echo '<tr style="background:#f5f5f5;">';
        echo '  <th>商品图片</th>';
        echo '  <th>商品ID</th>';
        echo '  <th>价格范围</th>';
        echo '  <th>90天销量</th>';
        echo '  <th>服务保障</th>';
        echo '  <th>商品标题</th>';
        echo '  <th>SKU数</th>';
        echo '</tr>';

        foreach ($goods_list as $item) {
            //dump($item);die;
            //dump($item['serviceList']);die;
            // 处理服务项
            $services = array_column($item['serviceList'], 'name');

            echo '<tr>';
            echo '  <td><img src="'.htmlspecialchars($item['imgUrl']).'" width="80"></td>';
            echo '  <td>'.htmlspecialchars($item['itemId']).'</td>';
            echo '  <td>¥'.htmlspecialchars($item['minPrice']/100).' - ¥'.htmlspecialchars($item['maxPrice']/100).'</td>';
            echo '  <td>'.number_format(isset($item['salesCnt90d'])?$item['salesCnt90d']:0).'</td>';
            echo '  <td>'.htmlspecialchars(implode('，', $services)).'</td>';
            echo '  <td style="max-width:300px;">'.htmlspecialchars($item['title']).'</td>';
            echo '  <td>'.$item['skuCnt'].'</td>';
            echo '</tr>';
        }

        echo '</table>';
    }
    function testtool(){

        return view();
    }

    function testwss(){
        return view();
    }

    /**
     * desc：签名测试
     *
     * index/test/signTest
     *
     * author：wh
     */
    function signtest(){
        $input_params = [
            'timestamp'=>input('timestamp')?:time(),
            'noncestr'=>input('noncestr')?:'noncestr',
            'goods_id'=>1,
            'buy_num'=>1,
            'useraddress_id'=>1,
            'users_id'=>1,
            'openid'=>'or9D2vs863Ky5Py2ovkAiu9XFLO4'
        ];
        $sign = Tools::signature($input_params);
        $input_params['sign'] = $sign;

        dump($input_params);
    }

    function buildApiDoc()
    {
        $obj = new ApiDocument();
        //根据自己的实际情况设置直接继承类（仅供参考）
        $obj->extends_base_class = 'app\\api\\controller\\BaseHttpApi,wanghua\\general_utility_tools_php\\framework\\base\\BaseWechatAuthController';
        //设置过滤的类（仅供参考）
        $obj->setFilterClass([
            'BaseCommonController',
            'BaseHttpApi',
            'BaseWssApi',
            'Wsspush',
            'BaseController',
            'BaseAuthController',
            //'BaseWechatAuthController',
            'BasePublicController'
        ]);
        $obj->setFilterFunction([
            'buildApiDoc',
            'buildTablesConf',
            'checkfailed',
            'clearCache',
            'defaultAuth',
            'operateLog',
            'checkMaintain',
            '_empty'
        ]);
        //构建接口文档
        $obj->buildDoc();
        //生成html
        $html = $obj->buildApiDocHtml();
        $path = Tools::get_root_path().'/public/api_docs/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
        file_put_contents($path.'api_list.html',$html);
        echo "<a href='/api_docs/api_list.html' target='_blank'>api_list.html</a>";
    }

    public function buildTablesConf()
    {
        parent::buildTablesConf(); // TODO: Change the autogenerated stub
    }
    public function clearCache()
    {
        parent::clearCache(); // TODO: Change the autogenerated stub

    }
    function fileupload(){
        return view();
    }


    function ssetest(){
        return view();
    }



    function sse() {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no');
        $rsp = [];
        $config = [
            'stream'=>true,
        ];
        $question = '你好';
        $ai_config = config('deepseek');
        $url = $ai_config['chat']['base_url'];
        $apiKey = $ai_config['chat']['APIKey'];
        $model = $ai_config['chat']['model'];

        $obj = (new F37A49CDED4199801B05D5FFFAF78E010());
        $obj->chatId = time();//确保唯一
        $obj->url = $url;
        $obj->apiKey = $apiKey;
        $obj->model = $model;
        $items = [];
        $obj->s8EB5A47634F626B142D2A93E9BAF009F($items);
        $obj->cAA8AF3EBE14831A7CD1B6D1383A03755($question,$config,$rsp);
    }

}